package com.m7788.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.m7788.screen.R;

public class ImageUpload {
	private static File cacheDir;
	private static Context mContext;
	private static ImageUpload instance;
	
	public ImageUpload(Context context){
		mContext = context;
		setFileDir();
	}
	
	
	public static ImageUpload getInstance(Context context)
    {
         if(null == instance)
         {
            instance = new ImageUpload(context);
         }
        return instance;             
    }
	
	public  void setContext(Context context){
//		if(mContext == null){
//			mContext =context;
//			setFileDir();
//		}
		
	}
	public  void releaseContext(){
//		mContext = null;
	}
	
	private  void setFileDir(){
    	// 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
        // 没有SD卡就放在系统的缓存目录中
        if (android.os.Environment.getExternalStorageState().equals(
                        android.os.Environment.MEDIA_MOUNTED))
                cacheDir = new File(
                                android.os.Environment.getExternalStorageDirectory(),
                                Constant.IMAGEPATH);
        else
                cacheDir = mContext.getCacheDir();
        if (!cacheDir.exists())
                cacheDir.mkdirs();
    }
	public  File getFileDir(){
		return cacheDir;
	}
	
	public  String saveBitmapReturnPath(Bitmap bm,int maxSize){
		String path =  writeToCache(bm,maxSize);
		 return path;
	}
	/**
	 * 
	 * 方法名：formatFileFromBitmap 
	 * 功能：单张图片转换为file，适用于即拍即传、相册单张图片（可能有旋转）
	 * 参数：
	 * @param bm
	 * @return
	 * 创建人：huanghaishui  
	 * 创建时间：2013-9-1
	 */
	public  File formatFileFromBitmap(Bitmap bm,int maxSize){
		 String path =  writeToCache(bm,maxSize);
		 //int degree = AppUtil.readPictureDegree(path);
		 File file = readFromUri(path,0,maxSize);
		 return file;
	}
	
	public  File formatFileFromBitmapSmall(Bitmap bm){
		Bitmap temp = zoomImg(bm);
		if (bm != null && !bm.isRecycled()){
			bm.recycle();
			bm=null;
		}
		String path =  writeToCache(temp,0);
		if (temp != null && !temp.isRecycled()){
			temp.recycle();
			temp=null;
       	 
		}
		 File file = readFromUriSmall(path,0);
		 System.gc();
		 return file;
	}
	
	

	
	public  File readFromUriSmall(String path,float degree){
		FileOutputStream fos = null;
	    BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();  
	    
    	bitmapFactoryOptions.inJustDecodeBounds = true;
    	Bitmap  bm;
    	bitmapFactoryOptions = changeOptionSmall(bitmapFactoryOptions);  
    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
    	bm = zoomImg(bm);
    	Bitmap bm2=AppUtil.rotate(bm, degree);
    	String fileName=path.substring(path.lastIndexOf("/")+1,path.length());
        File small =new File(cacheDir,"s_"+fileName);
        try {
			fos = new FileOutputStream(small);
			bm2.compress(Bitmap.CompressFormat.JPEG, 80, fos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
             try {
            	 if(fos!=null){
            		 fos.flush();
                	 fos.close();
                	 bm2.recycle();
                	 bm2= null;
             			System.gc();
            	 }
            	 
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
		return small;
		
	}
	
	/**
	 * 
	 * 方法名：readBitmapFromPath 
	 * 功能：单张图片的展示
	 * 参数：
	 * @param path
	 * @return
	 * 创建人：huanghaishui  
	 * 创建时间：2013-9-1
	 */
	public static Bitmap readBitmapFromPath(String path){
		BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();  
	    
    	bitmapFactoryOptions.inJustDecodeBounds = true;
    	Bitmap  bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
    	bitmapFactoryOptions = changeOption(bitmapFactoryOptions);  
    	//按比例压缩
    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
    	return bm;
	}
	
	/**
	 * 
	 * 方法名：writeToCache 
	 * 功能：将图片写入文件
	 * 参数：
	 * @param bitmap
	 * @return
	 * 创建人：huanghaishui  
	 * 创建时间：2013-8-7
	 */
	public static String writeToCache(Bitmap bitmap,int maxSize){
		FileOutputStream fos = null;
		File small=null;
		try {
			small =new File(cacheDir,new Date().getTime()+".jpg");
       	 	fos = new FileOutputStream(small);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);// 把数据写入文件
//            if(small!=null&&maxSize>0){
//            	computeFileSize(small,maxSize);
//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
           	 if(fos!=null){
           		 fos.flush();
               	 fos.close();
               	
           	 }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return small.getAbsolutePath();
	}
	
	/**
	 * 
	 * 方法名：changeOption 
	 * 功能：计算比例压缩的比例
	 * 参数：
	 * @param bitmapFactoryOptions
	 * @return
	 * 创建人：huanghaishui  
	 * 创建时间：2013-8-7
*/	
	public static BitmapFactory.Options changeOption(BitmapFactory.Options bitmapFactoryOptions){
 		//png 建议300 jpg
		
		
		//int yRatio = (int)Math.ceil(bitmapFactoryOptions.outHeight/2000);   
    	//int xRatio = (int)Math.ceil(bitmapFactoryOptions.outWidth/2000); 
		//double d=3.14159;
		double  yRatio =bitmapFactoryOptions.outHeight/2048.0;   
		double  xRatio =bitmapFactoryOptions.outWidth/2048.0; 
		//Log.e("d",d+"");
		// Log.e("yRatio",yRatio+"");
		// Log.e("xRatio",xRatio+"");
		//  Log.e("bitmapFactoryOptions.outHeight",bitmapFactoryOptions.outHeight+"");
		 double all_Ratio=0;
		
	    	if (yRatio > 1 || xRatio > 1){   
	    		 if (yRatio > xRatio) {   
	    			 all_Ratio = yRatio;   
	    		    
	    		 }else {   
	    			 all_Ratio = xRatio;   
	    		 }    
	    	} 
	    
	   // Log.e("all_Ratio",all_Ratio+"");
	    	
	    if (all_Ratio<=1){
	    	bitmapFactoryOptions.inSampleSize=1;		
	    }else if (all_Ratio>1 && all_Ratio<2){
			bitmapFactoryOptions.inSampleSize=2;
	    }else if (all_Ratio>=2 && all_Ratio<4){
			bitmapFactoryOptions.inSampleSize=4;	
		}else if (all_Ratio>=4){
			bitmapFactoryOptions.inSampleSize=8;
		}		
		// Log.e("bitmapFactoryOptions.inSampleSize",bitmapFactoryOptions.inSampleSize+"");
		bitmapFactoryOptions.inJustDecodeBounds = false;  
 		return bitmapFactoryOptions;
 		
 	}
	 
	
	
	
	public static BitmapFactory.Options changeOptionSmall(BitmapFactory.Options bitmapFactoryOptions){
 		//png 建议300 jpg
		int yRatio = (int)Math.ceil(bitmapFactoryOptions.outHeight/120);   
    	int xRatio = (int)Math.ceil(bitmapFactoryOptions.outWidth/120); 
	    	if (yRatio > 1 || xRatio > 1){   
	    		 if (yRatio > xRatio) {   
	    		  bitmapFactoryOptions.inSampleSize = yRatio;   
	    		    
	    		 }else {   
	    		  bitmapFactoryOptions.inSampleSize = xRatio;   
	    		 }    
	    	} 
		    bitmapFactoryOptions.inJustDecodeBounds = false;  
 		return bitmapFactoryOptions;
 		
 	}
	

	
	
	
    /**
     * 
     * 方法名：getRealPathFromURI 
     * 功能：将图片uri转换为String地址
     * 参数：
     * @param contentUri
     * @return
     * 创建人：huanghaishui  
     * 创建时间：2013-8-4
     */
    public static String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        ContentResolver resolver = mContext.getContentResolver();  
        Cursor cursor = resolver.query(contentUri, proj, null, null, null);
        int column_index
        	= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }
    
    /**
     * 
     * 方法名：createBitMap 
     * 功能：水印制作
     * 参数：
     * @param src
     * @return
     * 创建人：huanghaishui  
     * 创建时间：2013-8-6
     */
    private  Bitmap createWaterMark(Bitmap src){
    	
    	if(src==null){
    		return null;
    	}
    	int w=src.getWidth();
    	int h=src.getHeight();
    	
//    	Bitmap wmsrc=BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wa1);//水印
//    	int wmw=wmsrc.getWidth();
//    	int wmh=wmsrc.getHeight();
    	//create the new bitmap
    	Bitmap newb=Bitmap.createBitmap(w,h,Config.ARGB_8888);//创建一个底图
    	Canvas cv=new Canvas(newb);
    	//将底图画进去
    	cv.drawBitmap(src, 0, 0,null);//在0,0坐标开始画入src
    	if (src != null && !src.isRecycled()) {
    		src.recycle();
    		src= null;
    		System.gc();
    	}
    	int resId = getWaterImage(w,h);
    	Bitmap wmsrc = drawableToBitmap(resId);
    	//讲水印画进去
    	
    	Log.e("源图宽度:",w+"");
    	Log.e("源图高度:",h+"");
    	
    	Log.e("水印宽度:",wmsrc.getWidth()+"");
    	Log.e("水印高度:",wmsrc.getHeight()+"");
    	
    	Log.e("water_width:",get_water_width(resId)+"");
    	
    	cv.drawBitmap(wmsrc, w-get_water_width(resId)-5, 5, null);
    	//保存图片
    	cv.save(Canvas.ALL_SAVE_FLAG);
    	cv.restore();
    	return newb;

    	}
    public static Bitmap zoomImg(Bitmap bm){
		Bitmap newb=Bitmap.createBitmap(120,120,Config.ARGB_8888);
    	if(bm!=null){
			// 获得图片的宽高
			int width = bm.getWidth();
			int height = bm.getHeight();
			// 计算缩放比例
			float scaleWidth=0;
			int x=0;
			int y=0;
			if(width>height){
				scaleWidth = ((float) 120) / width;
				y=(int)(120-height*scaleWidth)/2;
			}else{
				scaleWidth = ((float) 120) / height;
				x=(int)(120-width*scaleWidth)/2;
			}


			// 取得想要缩放的matrix参数
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleWidth);
			// 得到新的图片   www.2cto.com
			Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
			//图片补白
			//创建一个底图
			Canvas cv=new Canvas(newb);
			//将底图画进去
			cv.drawColor(Color.WHITE);
			cv.drawBitmap(newbm, x, y,null);//在0,0坐标开始画入src
			if (newbm != null && !newbm.isRecycled()) {
				newbm.recycle();
				newbm= null;
				System.gc();
			}
			cv.save(Canvas.ALL_SAVE_FLAG);
			cv.restore();
		}
        return newb;
    }  
    /**
     * 
     * 方法名：drawableToBitmap 
     * 功能：因为读取出来的图片大小不一致，重新画图片大小
     * 参数：
     * @return
     * 创建人：huanghaishui  
     * 创建时间：2013-8-17
     */
    private  Bitmap drawableToBitmap(int resId) { 
    	Drawable drawable = mContext.getResources().getDrawable(resId);
        Bitmap bitmap = Bitmap.createBitmap(
                                        drawable.getIntrinsicWidth(),
                                        drawable.getIntrinsicHeight(),
                                        drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
                                                        : Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        switch (resId){
			case R.drawable.wa1:
				drawable.setBounds(0, 0, 100, 27);
				break;
			case R.drawable.wa2:
				drawable.setBounds(0, 0, 150, 41);
				break;
			case R.drawable.wa3:
				drawable.setBounds(0, 0, 200, 55);
				break;
			case R.drawable.wa4:
				drawable.setBounds(0, 0, 250, 69);
				break;
			case R.drawable.wa5:
				drawable.setBounds(0, 0, 300, 83);
				break;
			case R.drawable.wa6:
				drawable.setBounds(0, 0, 350, 96);
				break;
			case R.drawable.wa7:
				drawable.setBounds(0, 0, 400, 110);
				break;
			case R.drawable.wa8:
				drawable.setBounds(0, 0, 450, 124);
				break;
			case R.drawable.wa9:
				drawable.setBounds(0, 0, 500, 138);
				break;
			case R.drawable.wa10:
				drawable.setBounds(0, 0, 550, 151);
				break;
			default:
				drawable.setBounds(0, 0, 100, 27);
				break;
        }
        
        drawable.draw(canvas);
        return bitmap;
}
    
    public int get_water_width(int resId){    	
    	switch (resId){
		case R.drawable.wa1:
			return 100;

		case R.drawable.wa2:
			return 150;

		case R.drawable.wa3:
			return 200;

		case R.drawable.wa4:
			return 250;

		case R.drawable.wa5:
			return 300;

		case R.drawable.wa6:
			return 350;

		case R.drawable.wa7:
			return 400;

		case R.drawable.wa8:
			return 450;

		case R.drawable.wa9:
			return 500;

		case R.drawable.wa10:
			return 550;
	
		default:
			return 100;

    }
    }
    public static void sendMesToActivity(int flag,String desc){//显示提示信息
	      Intent intent = new Intent();
		  intent.putExtra("operation", flag);
		  intent.putExtra("desc", desc);
		  intent.setAction(Constant.ACTION_STOA);
		  mContext.sendBroadcast(intent); 
	    }
    
    /**
     * 
     * 方法名：getWaterImage 
     * 功能：挑选水印图片
     * 参数：
     * @param w
     * @param h
     * @return
     * 创建人：huanghaishui  
     * 创建时间：2013-8-6
     */
    private static int getWaterImage(int w,int h){
    	int a=0;
    	int b=0;
    	int flag=1;
    	int res=R.drawable.wa1;
    	int width = (w / 4) ;
    	if(width<=100 ){
    		a=1;
    	}else if(width>100 && width<=150){
    		a=2;
    	}else if(width>150 && width<=200){
    		a=3;
    	}else if(width>200 && width<=250){
    		a=4;
    	}else if(width>250 && width<=300){
    		a=5;
    	}else if(width>300 && width<=350){
    		a=6;
    	}else if(width>350 && width<=400){
    		a=7;
    	}else if(width>400 && width<=450){
    		a=8;
    	}else if(width>450 && width<=500){
    		a=9;
    	}else if(width>500 ){
    		a=10;
    	}

    	int height = (h / 8);
    	if(height<=29 ){
    		b=1;
    	}else if(height>29 && height<=44){
    		b=2;
    	}else if(height>44 && height<=58){
    		b=3;
    	}else if(height>58 && height<=73){
    		b=4;
    	}else if(height>73 && height<=87){
    		b=5;
    	}else if(height>87 && height<=101){
    		b=6;
    	}else if(height>101 && height<=115){
    		b=7;
    	}else if(height>115 && height<=129){
    		b=8;
    	}else if(height>129 && height<=143){
    		b=9;
    	}else if(height>143 ){
    		b=10;
    	}

    	if(a<b){
    		flag=a;
    	}else {
    		flag=b;
    	}
    	switch (flag){
    		case 1:
	    		res = R.drawable.wa1;
	    		break;
    		case 2:
	    		res = R.drawable.wa2;
	    		break;
    		case 3:
	    		res = R.drawable.wa3;
	    		break;
    		case 4:
	    		res = R.drawable.wa4;
	    		break;
    		case 5:
	    		res = R.drawable.wa5;
	    		break;
    		case 6:
	    		res = R.drawable.wa6;
	    		break;
    		case 7:
	    		res = R.drawable.wa7;
	    		break;
    		case 8:
	    		res = R.drawable.wa8;
	    		break;
    		case 9:
	    		res = R.drawable.wa9;
	    		break;
    		case 10:
	    		res = R.drawable.wa10;
	    		break;
    	}
    	
    	Log.e("flag:", flag+"");
    	
    	return res;
    }
   
  
    public  File readFromUri(String path,float degree,int maxSize){
		Bitmap  bm = null;
		File small = null;		
		FileOutputStream fos = null;
		int inSampleSize=get_inSampleSize(path);
		
		if(AppUtil.computeFileSize(path)>maxSize){
	    	
	    	BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();  
	    	bitmapFactoryOptions.inSampleSize=inSampleSize;		    	
	    	bitmapFactoryOptions.inJustDecodeBounds = false;
	    	//按比例压缩
	    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
	    	 String tempPath = writeToCache(bm, -1);
	    	int f_size=AppUtil.computeFileSize(tempPath);
	    	Log.e("原始大小",f_size+"");
	    	Log.e("原始maxsize",maxSize+"");
	    	while (f_size>maxSize){	    		
	    		Log.e("大小",f_size+"");
	    		Log.e("变化后maxsize=",maxSize+"");
	    		inSampleSize*=2;
	    		
	    		
	            bitmapFactoryOptions.inSampleSize=inSampleSize;		    	
			    bitmapFactoryOptions.inJustDecodeBounds = false; 		    	
		    	//Log.e("inSampleSize",inSampleSize+"");		    	
		    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
	    	    tempPath = writeToCache(bm, -1);
	            f_size = AppUtil.computeFileSize(tempPath);	            
	    	}
	    	
	    	Bitmap bm2=AppUtil.rotate(bm, degree);
	    	if(needWater()){
				bm2 = createWaterMark(bm2);
			}
	    	String fileName=path.substring(path.lastIndexOf("/")+1,path.length());
	        small =new File(cacheDir,fileName);
	        try {
				fos = new FileOutputStream(small);
	            bm2.compress(Bitmap.CompressFormat.JPEG, 80, fos);
	             
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
	             try {
	            	 if(fos!=null){
	            		 fos.flush();
	                	 fos.close();
	                	 bm2.recycle();
	                	 bm2=null;
	                	 System.gc();
	            	 }
	            	 
	             } catch (IOException e) {
	                 e.printStackTrace();
	             }
	         }
		}else{
			
			bm = BitmapFactory.decodeFile(path);
			Bitmap bm2=AppUtil.rotate(bm, degree);
			if(needWater()){
				bm2 = createWaterMark(bm2);
			}
	    	String fileName=path.substring(path.lastIndexOf("/")+1,path.length());
	        small =new File(cacheDir,fileName);
	        try {
				fos = new FileOutputStream(small);
	            bm2.compress(Bitmap.CompressFormat.JPEG, 80, fos);
	            
	           //Log.e("new_file_size", AppUtil.computeFileSize(fileName)+"");
	            
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
	             try {
	            	 if(fos!=null){
	            		 fos.flush();
	                	 fos.close();
	                	 bm2.recycle();
	                	 bm2=null;
	                	 System.gc();
	            	 }
	            	 
	             } catch (IOException e) {
	                 e.printStackTrace();
	             }
	         }
		}
		//if (bm != null && !bm.isRecycled())		bm.recycle();
		return small;
		
	}

	private boolean needWater() {
    	return AppUtil.getRecord(mContext,Constant.CLOSE_WATER).equals("false");
	}


	public  Bitmap readFromPath(String path,float degree,int maxSize){
		Bitmap  bm = null;
		Bitmap bm2 = null;
		int inSampleSize=get_inSampleSize(path);
		
		if(AppUtil.computeFileSize(path)>maxSize){
	    	
	    	BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();  
	    	bitmapFactoryOptions.inSampleSize=inSampleSize;		    	
	    	bitmapFactoryOptions.inJustDecodeBounds = false;
	    	//按比例压缩
	    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
	    	 String tempPath = writeToCache(bm, -1);
	    	int f_size=AppUtil.computeFileSize(tempPath);
	    	Log.e("原始大小",f_size+"");
	    	Log.e("原始maxsize",maxSize+"");
	    	while (f_size>maxSize){	    		
	    		
	    		
	    		Log.e("变化大小",f_size+"");
	    		Log.e("变化maxsize=",maxSize+"");
	    		inSampleSize*=2;
	            bitmapFactoryOptions.inSampleSize=inSampleSize;		    	
			    bitmapFactoryOptions.inJustDecodeBounds = false; 		    	
		    	//Log.e("inSampleSize",inSampleSize+"");		    	
		    	bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
	    	    tempPath = writeToCache(bm, -1);
	            f_size = AppUtil.computeFileSize(tempPath);	            
	    	}
	    	
	    	bm2=AppUtil.rotate(bm, degree);

		}else{
			
			bm = BitmapFactory.decodeFile(path);
			bm2=AppUtil.rotate(bm, degree);
			
		}
		return bm2;
		//return null;
    }



public static int get_inSampleSize(String path){
	
//	Log.e("path", path+"");
	
	BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options();	    
 	bitmapFactoryOptions.inJustDecodeBounds = true;
 	Bitmap  bm = BitmapFactory.decodeFile(path,bitmapFactoryOptions);
 	
	int heights = bitmapFactoryOptions.outHeight;   
	int widths = bitmapFactoryOptions.outWidth; 
	
	int v=0;
	
	Log.e("heights", heights+"");
	Log.e("widths", widths+"");
	
	if (bm != null && !bm.isRecycled())	{	
		bm.recycle();
		bm=null;
   	 	System.gc();
	}
	int inSampleSize=1;
	
	if (heights>widths){
		v=heights;	
	}else{
		v=widths;	
	}
	
//	if (heights > widths && heights>1024){   
//		inSampleSize=(int)(heights/1024);
//	} else {
//		if(widths > 1024){
//		inSampleSize=(int)(widths/1024);  
//		}
//	}

//	if(inSampleSize % 2>0 && v>1500 ){		
//		inSampleSize++;
//	}
//    
	
	while (v>1500){	 
		inSampleSize*=2;
		v=v/2;
	}
	
	Log.e("inSampleSize", inSampleSize+"");
	return inSampleSize;
	
	}
}